package com.my.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 文件读写工具
 * <dl>
 * <dt>作用:</dt>
 * <dd>1.读取文件保存在字符串中</dd>
 * <dd>2.写出文件</dd>
 * <dd>3.一行一行的读取文件保存在List&lt;String&gt;中</dd>
 * </dl>
 * 
 * @author zc
 */
public class FileUtil {
	private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

	public static final String DEFAULT_ENCODING = "UTF-8";
	public static final int MAX_BUFFER_SIZE = 1024;

	/**
	 * 使用UTF-8编码格式读取文件到字符串
	 * 
	 * @param path
	 *            文件路径
	 * @return 文件内容字
	 * @throws Exception
	 */
	public static String readFile(String path) throws Exception {

		return readFile(path, DEFAULT_ENCODING);
	}

	/**
	 * 读取文件到字符串
	 * 
	 * @param path
	 *            文件路径
	 * @param encoding
	 *            编码格式
	 * @return 文件内容字符
	 * @throws Exception
	 */
	public static String readFile(String path, String encoding)
			throws Exception {

		File file = new File(path);
		FileInputStream fis = null;
		InputStreamReader reader = null;
		StringBuffer output = new StringBuffer();

		try {
			fis = new FileInputStream(file);
			reader = new InputStreamReader(fis, encoding);
			char[] buffer = new char[MAX_BUFFER_SIZE];
			int n = MAX_BUFFER_SIZE;
			while ((n = reader.read(buffer, 0, MAX_BUFFER_SIZE)) != -1) {
				output.append(buffer, 0, n);
			}

		} catch (FileNotFoundException e) {
			throw e;
		} catch (IOException e) {
			throw e;
		} catch (Exception e) {
			throw e;
		} finally {

			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return output.toString();
	}

	/**
	 * 使用UTF-8编码格式将字符串写入文件
	 * 
	 * @param content
	 *            写入内容字符
	 * @param path
	 *            文件路径
	 * @return 成功 true 失败false
	 */
	public static boolean writeFile(String content, String path) {

		return writeFile(content, path, DEFAULT_ENCODING);
	}

	/**
	 * 将字符串写入文件
	 * 
	 * @param content
	 *            写入内容字符
	 * @param path
	 *            文件路径
	 * @param encoding
	 *            编码格式
	 * @return 成功 true 失败false
	 */
	public static boolean writeFile(String content, String path, String encoding) {

		File file = new File(path);
		File parentFile = new File(file.getParent());
		FileOutputStream fos = null;
		OutputStreamWriter writer = null;

		try {
			if (!parentFile.exists()) {
				parentFile.mkdirs();
			}
			if (!file.exists()) {
				file.createNewFile();
			}

			fos = new FileOutputStream(file);
			writer = new OutputStreamWriter(fos, encoding);
			writer.write(content);

		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {

			if (writer != null) {
				try {
					writer.close();
					writer = null;
				} catch (Exception e) {
					e.printStackTrace();
					return false;
				}
			}

			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
					return false;
				}
			}
		}

		return true;
	}

	/**
	 * 获取类在文件系统的路
	 * 
	 * @param clazz
	 *            目标
	 * @return 路径
	 */
	public static String getClassFolderPath(Class<?> clazz) {

		ClassLoader loader = clazz.getClassLoader();
		String packagePath = clazz.getPackage().getName().replace('.', '/');
		String url = loader.getResource(packagePath).getPath();
		try {
			url = URLDecoder.decode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
		return url;
	}

	/**
	 * 读取文件内容，以行为单位生成字符串列
	 * 
	 * @param path
	 *            文件路径
	 * @return 字符串列
	 * @throws Exception
	 */
	public static List<String> readFileToLines(String path) throws Exception {

		File file = new File(path);
		FileReader fr = null;
		BufferedReader reader = null;
		List<String> content = new ArrayList<String>();

		try {
			fr = new FileReader(file);

			reader = new BufferedReader(fr);
			String buffer = null;
			while ((buffer = reader.readLine()) != null) {
				content.add(buffer.trim());
			}
		} catch (FileNotFoundException e) {
			throw e;
		} catch (IOException e) {
			throw e;
		} catch (Exception e) {
			throw e;
		} finally {

			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (fr != null) {
				try {
					fr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return content;
	}

	public static void main(String[] args) throws Exception {
		System.out.println(readFile("C:\\Users\\zc\\Desktop\\Linux下载地址.txt"));
		List<String> lines = readFileToLines("C:\\Users\\zc\\Desktop\\Linux下载地址.txt");
		System.out.println("\n" + lines.get(2));
		writeFile("这个数字第三方士大夫水电费是的发送的", "C:\\Users\\zc\\Desktop\\test.txt");
	}
}
